package com.database.management.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.database.management.common.Result;
import com.database.management.common.ResultCode;
import com.database.management.service.CommandService;
import com.mysql.jdbc.StringUtils;

/**
 * Servlet implementation class IndexController
 */
@WebServlet("/CommandController")
public class CommandController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public CommandController() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8"); 
		Result result = distribution(request);
		try {
			response.getWriter().append(JSON.toJSONString(result.getResult()));
		} catch (Exception e) {
			result.setStatusCode(ResultCode.DB_ERROR.getCode());
			result.setMessage(ResultCode.DB_ERROR.getMessage());
			response.getWriter().append(JSON.toJSONString(result));
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private Result distribution(HttpServletRequest request){
		String key = request.getParameter("key");
		Integer keyI = null;
		if(!StringUtils.isNullOrEmpty(key)){
			keyI = Integer.valueOf(key);
		}
		CommandService commandService = new CommandService(keyI);
		Result result = new Result();
		result.setStatusCode(ResultCode.DB_SUCCESS.getCode());
		result.setMessage(ResultCode.DB_SUCCESS.getMessage());
		String sql = request.getParameter("sql");
		if(sql == null){
			sql = "";
		}
		try {
			if(sql.toLowerCase().indexOf("select") != -1){
				result.setResult(commandService.find(sql));
			}else if(sql.toLowerCase().indexOf("show") != -1){
				result.setResult(commandService.getAllTableName());
			}else{
				result.setResult(commandService.update(sql));
			}
		} catch (Exception e) {
			result.setStatusCode(ResultCode.DB_ERROR.getCode());
			result.setMessage(ResultCode.DB_ERROR.getMessage());
			e.printStackTrace();
		}
		return result;
	}

}
